<template>
  <NotificationDispatcher />
  <div class="page-banner">
    <div class="banner-content">
      <div>
        <h2 class="banner-title">欢迎使用会议室管理系统</h2>
        <p class="banner-subtitle">高效管理您的会议室使用情况</p>
      </div>
    </div>
  </div>

  <div class="stats-container">
    <div class="stat-card">
      <div class="stat-value">{{ availableRooms }}</div>
      <div class="stat-label">可用会议室</div>
    </div>
    <div class="stat-card">
      <div class="stat-value">{{ inUseRooms }}</div>
      <div class="stat-label">使用中会议室</div>
    </div>
    <div class="stat-card">
      <div class="stat-value">{{ `${timeSlotAvailability}%` }}</div>
      <div class="stat-label">今日剩余时间段可用率</div>
    </div>
  </div>

  <div class="chart-container">
    <div class="chart-wrapper">
      <div class="chart-title">会议室使用状态</div>
      <div ref="usageChart" class="chart"></div>
    </div>

    <div class="chart-wrapper">
      <div class="chart-title">今日时间段可用情况</div>
      <div ref="timeSlotChart" class="chart"></div>
    </div>
  </div>

  <div class="room-map">
    <div
        v-for="room in rooms"
        :key="room.id"
        class="room-block"
        :class="{ occupied: room.inUse, available: !room.inUse }"
        @click="selectRoom(room)"
    >
      <div class="room-icon">🏢</div>
      <div class="room-name">{{ room.name }}</div>
      <div class="room-status">{{ room.seats }} 个座位</div>
    </div>
  </div>

  <el-card v-if="isAdmin" class="box-card" style="margin-top: 20px">
    <template #header>
      <span>黑名单状态变更日志</span>
    </template>
    <el-table :data="blacklistLogs" style="width: 100%">
      <el-table-column prop="user" label="用户" width="150" />
      <el-table-column prop="action" label="操作" width="150" />
      <el-table-column prop="date" label="时间" />
    </el-table>
  </el-card>

  <el-dialog v-model="dialogVisible" title="会议室使用详情" width="500px">
    <template #default>
      <p><strong>会议室：</strong>{{ selectedRoom?.name }}</p>
      <p><strong>座位数：</strong>{{ selectedRoom?.seats }}</p>
      <p><strong>预约信息：</strong></p>
      <ul v-if="selectedRoom?.bookings?.length">
        <li v-for="(booking, index) in selectedRoom.bookings" :key="index">
          {{ booking.user }}：{{ booking.start }} - {{ booking.end }}
        </li>
      </ul>
      <p v-else>{{ selectedRoom.inUse ? "暂无预约" : "该会议室当前空闲" }}</p>

      <p><strong>配备器材：</strong></p>
      <ul v-if="selectedRoom?.equipment?.length">
        <li v-for="(item, index) in selectedRoom.equipment" :key="index">
          {{ item }}
        </li>
      </ul>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import dayjs from 'dayjs';
import NotificationDispatcher from '../../components/NotificationDispatcher.vue';

const userStr = localStorage.getItem('user')
const isAdmin = ref(false)
// 统计可用和使用中会议室数量
const availableRooms = computed(() => rooms.value.filter(r => !r.inUse).length);
const inUseRooms = computed(() => rooms.value.filter(r => r.inUse).length);

if (userStr) {
  try {
    const user = JSON.parse(userStr)
    isAdmin.value = user.role === 'admin'
  } catch (e) {
    console.error('解析用户信息失败')
  }
}

const blacklistLogs = ref([
  { user: '张三', action: '加入黑名单', date: '2025-06-30 10:05' },
  { user: '李四', action: '自动解封', date: '2025-06-29 23:59' },
  { user: '王五', action: '加入黑名单', date: '2025-06-28 14:30' }
])


const names = ["张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十", "郑一", "冯二"];
const equipmentPool = [
  "投影仪", "电视", "麦克风", "音响", "白板",
  "视频会议设备", "录音设备", "激光笔", "显示屏", "无线分享器"
];

const generateEquipment = (seats: number) => {
  return seats === 10 ? equipmentPool : equipmentPool.sort(() => 0.5 - Math.random()).slice(0, Math.floor(Math.random() * 4) + 2);
};

const generateBooking = (roomId: number, inUse: boolean) => {
  if (!inUse) return [];
  const hour = Math.floor(Math.random() * 6) + 8;
  return [{
    roomId,
    user: names[Math.floor(Math.random() * names.length)],
    start: `${hour}:00`,
    end: `${hour + 2}:00`,
  }];
};

const rooms = ref(
    Array.from({ length: 30 }, (_, i) => {
      const id = i + 1;
      const buildingIndex = i % 7;
      const building = String.fromCharCode(65 + buildingIndex); // A-G
      const floor = Math.floor(i / 7) + 1;
      const roomNum = 100 + (i % 20);

      return {
        id,
        name: `${building}区${building}${floor}号楼${roomNum}`,
        inUse: Math.random() < 0.5,
        seats: [10, 30, 50, 150, 300][Math.floor(Math.random() * 5)],
        type: ['小型', '中型', '大型'][Math.floor(Math.random() * 3)],
        bookings: generateBooking(id, Math.random() < 0.5),
        equipment: generateEquipment([10, 30, 50, 150, 300][Math.floor(Math.random() * 5)])
      };
    })
);

const dialogVisible = ref(false);
const selectedRoom = ref<any>(null);

const selectRoom = (room: any) => {
  selectedRoom.value = room;
  dialogVisible.value = true;
};


const timeSlotAvailability = computed(() => {
  const now = new Date();
  const currentHour = now.getHours();
  if (currentHour >= 22) return 0;
  if (currentHour < 8) return 100;
  const totalSlots = 14;
  const passedSlots = currentHour - 8;
  return Math.round(((totalSlots - passedSlots) / totalSlots) * 100);
});

const usageChart = ref<HTMLElement | null>(null);
const timeSlotChart = ref<HTMLElement | null>(null);
let usageChartInstance: ECharts | null = null;
let timeSlotChartInstance: ECharts | null = null;

function initCharts() {
  if (usageChart.value) {
    usageChartInstance = echarts.init(usageChart.value);
    usageChartInstance.setOption({
      tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
      legend: { orient: 'vertical', left: 10, data: ['可用会议室', '使用中会议室'] },
      series: [{
        name: '会议室状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
        label: { show: false, position: 'center' },
        emphasis: { label: { show: true, fontSize: '18', fontWeight: 'bold' } },
        labelLine: { show: false },
        data: [
          { value: availableRooms.value, name: '可用会议室', itemStyle: { color: '#36a362' } },
          { value: inUseRooms.value, name: '使用中会议室', itemStyle: { color: '#e45649' } }
        ]
      }]
    });
  }

  if (timeSlotChart.value) {
    timeSlotChartInstance = echarts.init(timeSlotChart.value);
    const timeSlots: { name: string; value: number; itemStyle: Record<string, unknown> }[] = [];
    const now = new Date();
    const currentHour = now.getHours();
    for (let hour = 8; hour <= 22; hour++) {
      const isPast = hour < currentHour;
      const isCurrent = hour === currentHour;
      timeSlots.push({
        name: `${hour}:00-${hour + 1}:00`,
        value: isPast ? 0 : Math.max(100 - (hour - 8) * 5, 0),
        itemStyle: { color: isPast ? '#d3d3d3' : isCurrent ? '#f0a545' : '#4a8bed' }
      });
    }
    timeSlotChartInstance.setOption({
      tooltip: { trigger: 'item', formatter: '{b}: {c}% 可用' },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { type: 'category', data: timeSlots.map(s => s.name), axisLabel: { interval: 2, rotate: 45 } },
      yAxis: { type: 'value', max: 100, axisLabel: { formatter: '{value}%' } },
      series: [{
        name: '时间段可用率', type: 'bar', barWidth: '60%', data: timeSlots,
        label: { show: true, position: 'top', formatter: '{c}%' }
      }]
    });
  }
}

function handleResize() {
  usageChartInstance?.resize();
  timeSlotChartInstance?.resize();
}

onMounted(() => {
  nextTick(() => {
    initCharts();
    window.addEventListener('resize', handleResize);
  });
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  usageChartInstance?.dispose();
  timeSlotChartInstance?.dispose();
});
</script>

<style scoped>
.room-map {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
  gap: 20px;
  padding: 30px;
  background-color: #f5f7fa;
}

.room-block {
  border-radius: 12px;
  height: 100px;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  color: white;
  font-weight: 600;
}

.room-block:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
}

.room-block.occupied {
  background: linear-gradient(135deg, #f44336, #e57373);
}

.room-block.available {
  background: linear-gradient(135deg, #4caf50, #81c784);
}

.room-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.room-name {
  font-size: 15px;
}

.room-status {
  font-size: 13px;
  opacity: 0.9;
}
.stats-container {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
}
.stat-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  padding: 20px;
  text-align: center;
  width: 200px;
}
.stat-value {
  font-size: 2.5rem;
  font-weight: bold;
  color: #4a8bed;
  margin-bottom: 10px;
}
.stat-label {
  font-size: 1rem;
  color: #666;
}
.chart-container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
  margin: 30px 0;
}
.chart-wrapper {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  padding: 20px;
  width: 48%;
}
.chart-title {
  font-size: 1.2rem;
  font-weight: bold;
  text-align: center;
  margin-bottom: 15px;
  color: #333;
}
.chart {
  width: 100%;
  height: 300px;
}
.room-map {
  display: grid;
  grid-template-columns: repeat(auto-fill,minmax(130px,1fr));
  gap: 20px;
  padding: 30px;
  background-color: #f5f7fa;
}
.page-banner {
  background: linear-gradient(90deg, #4a8bed 0%, #36a362 100%);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}
.banner-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.banner-title {
  color: #fff;
  font-size: 1.75rem;
  margin: 0;
}
.banner-subtitle {
  color: rgba(255,255,255,0.8);
  margin-top: 4px;
}

.section-title {
  font-size: 1.25rem;
  font-weight: bold;
  margin-top: 0;
  margin-bottom: 16px;
  color: #333;
}
</style>
